package com.yangfei.mystudy1020.activity;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.yangfei.mystudy1020.R;

public class HandlerStudyAcitivity extends Activity {
    final static String TAG = "HandlerStudyAcitivity";
    final static int MSG_TEST1 = 1000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_handler);

        testThreadLocal();
        testHandler();
    }

    ThreadLocal mBooleanThreadLocal;
    ThreadLocal mBooleanThreadLocal2;

    /*
       ThreadLocal的set里面的实现是设置当前线程的变量
       Thread t = Thread.currentThread();
       所以即使同一个变量在不同线程的值是不一样的
     */
    private void testThreadLocal() {
        mBooleanThreadLocal = new ThreadLocal();
        mBooleanThreadLocal2 = new ThreadLocal();
        mBooleanThreadLocal.set(222);
        mBooleanThreadLocal2.set("super hero");
        Log.d(TAG, "[Thread#main]mBooleanThreadLocal=" + mBooleanThreadLocal.get());

        new Thread("Thread#1") {
            @Override
            public void run() {
                mBooleanThreadLocal.set(333);
                Log.d(TAG, "[Thread#1]mBooleanThreadLocal=" + mBooleanThreadLocal.get());
            }
        }.start();

        new Thread("Thread#2") {
            @Override
            public void run() {
                Log.d(TAG, "[Thread#2]mBooleanThreadLocal=" + mBooleanThreadLocal.get());
            }
        }.start();
    }

     Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what){
                case MSG_TEST1:{
                    Log.d(TAG,"get MSG_TEST1");
                    Log.d(TAG, "[Thread#main]mBooleanThreadLocal=" + mBooleanThreadLocal2.get());
                    break;
                }
            }
            return false;
        }
    });

    private void testHandler(){
        Message msg = new Message();
        Bundle bd = new Bundle();
        bd.putString("name","yangfei");
        msg.setData(bd);
        msg.what = MSG_TEST1;
        mHandler.sendMessageDelayed(msg,1000);
        Log.d(TAG,"send MSG_TEST1");
    }
}
